<template>
  <div class="employee-management">
    <!-- 选项卡 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab" class="employee-tabs">
        <el-tab-pane label="基本信息管理" name="info">
          <div class="tab-content">
            <!-- 搜索栏 -->
            <div class="search-section">
              <el-input v-model="searchKeyword" placeholder="搜索员工姓名" prefix-icon="Search" clearable
                style="max-width: 400px;width: 80%;margin-right: 10px" @input="handleEmployeeSearch" />
              <!--新增员工-->
              <el-button type="success" @click="handleAddEmployee">新增员工</el-button>
              <!--刷新按钮-->
              <el-button type="primary" @click="handleRefreshEmployees" :loading="employeeStore.loading"
                style="margin-left: 10px">
                刷新
              </el-button>
              <!--重置按钮-->
              <el-button @click="handleResetEmployeeSearch" style="margin-left: 10px" type="danger">
                重置
              </el-button>
            </div>


            <!-- 员工列表 -->
            <el-card class="employee-table-card">
              <el-table :data="employeeStore.employees" style="width: 100%" v-loading="employeeStore.loading"
                element-loading-text="加载中...">
                <el-table-column label="员工信息" width="250">
                  <template #default="scope">
                    <div class="employee-info">
                      <!--                      <el-avatar :size="40" :src="scope.row.avatar" />-->
                      <div class="employee-details">
                        <div class="employee-name">{{ scope.row.name }}</div>
                        <div class="employee-email">{{ scope.row.email }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="position" label="职位" width="120" />
                <el-table-column prop="joinDate" label="入职时间" width="120">
                  <template #default="scope">
                    {{ formatJoinDate(scope.row.joinDate) }}
                  </template>
                </el-table-column>
                <el-table-column label="资质证书" width="200">
                  <template #default="scope">
                    <div class="certifications">
                      <el-tag v-for="cert in scope.row.certifications" :key="cert" :type="getCertificationType(cert)"
                        size="small" class="cert-tag">
                        {{ cert }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button style="margin-right: 5px" type="primary" size="small" @click="handleEdit(scope.row)">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 16px; text-align: right;">
                <el-pagination background layout="total, prev, pager, next, sizes, jumper" :total="employeeStore.total"
                  :current-page="employeeCurrentPage" :page-size="employeePageSize" :page-sizes="[5, 10, 20, 50]"
                  @size-change="handleEmployeeSizeChange" @current-change="handleEmployeePageChange" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="排班管理" name="schedule">
          <div class="tab-content">
            <!-- 新增排班操作栏 -->
            <div class="schedule-actions">
              <el-button type="primary" @click="showBatchDialog = true">
                批量排班
              </el-button>

              <!-- 查询条件 -->
              <div class="schedule-search">
                <el-input v-model="scheduleSearch.name" placeholder="员工姓名" clearable
                  style="width: 150px; margin-right: 10px" />
                <el-date-picker v-model="scheduleSearch.dateRange" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width: 280px; margin-right: 10px" />

                <el-select v-model="scheduleSearch.shiftType" placeholder="班次类型" clearable
                  style="width: 120px; margin-right: 10px">
                  <el-option label="上午班" value="morning" />
                  <el-option label="下午班" value="afternoon" />
                  <el-option label="全天班" value="full-day" />
                </el-select>
                <el-button type="primary" @click="handleScheduleSearch">
                  查询
                </el-button>
                <el-button @click="resetScheduleSearch">重置</el-button>
              </div>
            </div>

            <!-- 视图切换 -->
            <div class="view-toggle">
              <el-radio-group v-model="scheduleView" size="small">
                <el-radio-button label="calendar">日历视图</el-radio-button>
                <el-radio-button label="list">列表视图</el-radio-button>
              </el-radio-group>
            </div>

            <!-- 日历视图 -->
            <el-card class="schedule-card" v-if="scheduleView === 'calendar'" v-loading="employeeStore.scheduleLoading">
              <div class="schedule-grid">
                <div v-for="day in filteredScheduleDays" :key="day.date" class="schedule-day">
                  <div class="day-header">
                    <span class="day-date">{{ day.date }}</span>
                  </div>
                  <div v-for="shift in day.shifts" :key="shift.id" class="shift-item"
                    :class="getShiftClass1(shift.type)">
                    <div class="shift-time">{{ shift.time }}</div>
                    <div class="shift-employee">{{ shift.employee }}</div>
                    <div class="shift-actions" v-if="shift.id && canEditShift(shift)">
                      <el-button size="small" type="danger" @click.stop="handleDeleteShift(shift)">
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 列表视图 -->
            <el-card class="schedule-card" v-else>
              <el-table :data="pagedShifts" style="width: 100%" v-loading="employeeStore.scheduleLoading">
                <el-table-column prop="employee" label="员工姓名" width="120" />
                <el-table-column prop="date" label="日期" width="120" />
                <el-table-column prop="time" label="班次时间" width="150" />
                <el-table-column prop="type" label="班次类型" width="120">
                  <template #default="scope">
                    <el-tag :type="getShiftTagType(scope.row.type)">
                      {{ formatShiftType(scope.row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="150" v-if="hasEditPermission">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="handleDeleteShift(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 16px; text-align: right;">
                <el-pagination background layout="total, prev, pager, next, sizes, jumper"
                  :total="employeeStore.scheduleTotal" v-model:current-page="scheduleCurrentPage"
                  v-model:page-size="schedulePageSize" :page-sizes="[5, 10, 20, 50]"
                  @size-change="handleScheduleSizeChange" @current-change="handleSchedulePageChange" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>



        <!-- 批量排班对话框 -->
        <el-dialog v-model="showBatchDialog" title="批量排班" width="600px">
          <el-form :model="batchForm" :rules="batchRules" ref="batchFormRef">
            <el-form-item label="选择员工" prop="employees">
              <el-select v-model="batchForm.employees" multiple placeholder="请选择员工" style="width: 100%"
                :default-limit="100">
                <template v-if="false">{{ console.log('员工下拉数据:', employeeStore.employees) }}</template>
                <el-option v-for="emp in employeeStore.allEmployees" :key="String(emp.employeeId ?? emp.id)"
                  :label="emp.name" :value="String(emp.employeeId ?? emp.id)" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择日期" prop="dates">
              <el-date-picker v-model="batchForm.dates" type="dates" placeholder="选择多个日期" style="width: 100%"
                :disabled-date="disablePastDate" />
            </el-form-item>
            <el-form-item label="班次类型" prop="shiftType">
              <el-select v-model="batchForm.shiftType" placeholder="请选择班次类型" style="width: 100%">
                <el-option label="上午班 (08:00-12:00)" value="morning" />
                <el-option label="下午班 (13:00-17:00)" value="afternoon" />
                <el-option label="全天班 (08:00-17:00)" value="full-day" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showBatchDialog = false">取消</el-button>
            <el-button type="primary" @click="handleBatchSchedule">确定</el-button>
          </template>
        </el-dialog>


        <el-tab-pane label="绩效评估" name="performance">
          <div class="tab-content">
            <!-- 查询表单 -->
            <el-card class="query-card">
              <el-form :model="performanceQuery" inline>
                <!--                <el-form-item label="员工姓名">-->
                <!--                  <el-input v-model="performanceQuery.employeeName" placeholder="请输入员工姓名" clearable style="width: 120px" />-->
                <!--                </el-form-item>-->
                <el-form-item label="绩效总分">
                  <el-input-number v-model="performanceQuery.minScore" placeholder="最低分" :min="0"
                    :precision="1"></el-input-number>
                  <span class="score-separator">-</span>
                  <el-input-number v-model="performanceQuery.maxScore" placeholder="最高分" :min="0"
                    :precision="1"></el-input-number>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handlePerformanceQuery">查询</el-button>
                  <el-button @click="resetPerformanceQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
            <!-- 查询结果表格 -->
            <el-card class="table-card">
              <el-table :data="pagedMergedPerformanceList" border stripe v-loading="employeeStore.performanceLoading"
                @sort-change="handlePerformanceSort" :default-sort="{ prop: 'totalScore', order: 'descending' }">
                <el-table-column prop="employeeName" label="员工姓名" sortable></el-table-column>
                <el-table-column prop="orderCount" label="订单总数" sortable></el-table-column>
                <el-table-column prop="salesAmount" label="销售额(元)" sortable>
                  <template #default="{ row }">
                    ¥{{ row.salesAmount.toLocaleString() }}
                  </template>
                </el-table-column>
                <el-table-column prop="attitudeScore" label="工作态度得分" sortable></el-table-column>
                <el-table-column prop="totalScore" label="绩效总分" sortable>
                  <template #default="{ row }">
                    <span :class="{ 'high-score': row.totalScore >= 90 }">
                      {{ row.totalScore }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="{ row }">
                    <el-button size="small" @click="handleEditPerformance(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDeletePerformance(row)"
                      :disabled="row.status !== 'draft'">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <div class="pagination">
                <el-pagination @size-change="handlePerformanceSizeChange" @current-change="handlePerformancePageChange"
                  :current-page="performancePagination.page" :page-sizes="[10, 20, 50, 100]"
                  :page-size="performancePagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                  :total="mergedPerformanceList.length">
                </el-pagination>
              </div>
            </el-card>
            <!-- 编辑绩效对话框 -->
            <el-dialog v-model="showPerformanceEditDialog" title="编辑绩效" width="400px">
              <el-form :model="performanceForm" :rules="performanceRules" ref="performanceFormRef" label-width="100px">
                <el-form-item label="员工姓名">
                  <el-input v-model="performanceForm.employeeName" disabled />
                </el-form-item>
                <el-form-item label="订单数">
                  <el-input v-model="performanceForm.orderCount" disabled />
                </el-form-item>
                <el-form-item label="销售额">
                  <el-input v-model="performanceForm.salesAmount" disabled />
                </el-form-item>
                <el-form-item label="工作态度得分" prop="attitudeScore">
                  <el-input-number v-model="performanceForm.attitudeScore" :min="0" :max="100" />
                </el-form-item>
                <el-form-item label="绩效总分">
                  <el-input v-model="performanceForm.totalScore" disabled />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showPerformanceEditDialog = false">取消</el-button>
                <el-button type="primary" @click="submitPerformanceEdit">保存</el-button>
              </template>
            </el-dialog>
          </div>
        </el-tab-pane>


      </el-tabs>
    </div>

    <!-- 编辑员工对话框 -->
    <el-dialog v-model="showEditDialog" :title="editingEmployee ? '编辑员工信息' : '新增员工'" width="50%">
      <el-form ref="employeeFormRef" :model="employeeForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
              <el-input v-model="employeeForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email" :rules="emailRules">
              <el-input v-model="employeeForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" required>
              <el-select v-model="employeeForm.position" placeholder="请选择职位" style="width: 100%">
                <el-option label="宠物美容师" value="宠物美容师" />
                <el-option label="兽医师" value="兽医师" />
                <el-option label="兽医助理" value="兽医助理" />
                <el-option label="前台接待" value="前台接待" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资质证书">
          <el-select v-model="employeeForm.certifications" multiple placeholder="请选择资质证书" style="width: 100%">
            <el-option label="美容师证" value="美容师证" />
            <el-option label="兽医执业证" value="兽医执业证" />
            <el-option label="兽医助理" value="兽医助理" />
            <el-option label="宠物营养师" value="宠物营养师" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间">
          <el-date-picker v-model="employeeForm.joinDate" value-format="YYYY-MM-DD" type="date" placeholder="选择入职日期"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEmployee">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useOrderStore } from '../stores/orderStore'
import { useEmployeeStore } from '../stores/employeeStore'
import { useProductOrderStore } from '../stores/productOrderStore'

const employeeStore = useEmployeeStore();
const productOrderStore = useProductOrderStore()

const employeeFormRef = ref();

// 响应式数据
const activeTab = ref('info')
const searchKeyword = ref('')
const showEditDialog = ref(false)
const editingEmployee = ref(null)
const performanceChart = ref(null)
const radarChart = ref(null)


// 排班数据现在从employeeStore.schedules获取

// 绩效指标
const performanceMetrics = ref([
  { label: '服务订单完成量', value: '234', growth: '12%' },
  { label: '客户评价得分', value: '4.8', growth: '5%' },
  { label: '销售业绩达成率', value: '96%', growth: '8%' }
])

// 员工表单
const employeeForm = ref({
  name: '',
  email: '',
  position: '',
  department: '',
  certifications: [],
  joinDate: ''
})

// 计算属性：过滤后的员工列表
const filteredEmployees = computed(() => {
  if (!searchKeyword.value) {
    return employeeStore.employees
  }
  return employeeStore.employees.filter(employee =>
    employee.name.includes(searchKeyword.value) ||
    employee.position.includes(searchKeyword.value) ||
    (employee.department && employee.department.includes(searchKeyword.value))
  )
})

// 方法
const formatJoinDate = (dateStr) => {
  if (!dateStr) return ''
  // 兼容后端返回的带T的时间字符串
  const d = dayjs(dateStr)
  if (d.isValid()) {
    return d.format('YYYY-MM-DD')
  }
  // 尝试只取前10位
  return dateStr.length >= 10 ? dateStr.slice(0, 10) : dateStr
}

const getCertificationType = (cert) => {
  // 为每种证书分配不同颜色
  const types = {
    '美容师证': 'success',
    '兽医执业证': 'primary',
    '兽医助理': 'warning',
    '宠物营养师': 'info',
    '客户服务证': 'danger',
    '宠物美容师高级证书': 'success',
    '动物医学本科': 'info',
    '动物医学专业': 'primary',
    '兽医学博士': 'danger',
    '执业兽医师': 'warning',
    // 可继续扩展
  }
  return types[cert] || 'info'
}

const handleAddEmployee = () => {
  editingEmployee.value = null
  Object.assign(employeeForm.value, {
    name: '',
    email: '',
    position: '',
    department: '',
    certifications: [],
    joinDate: ''
  })
  showEditDialog.value = true
}

const handleEdit = (employee) => {
  editingEmployee.value = employee
  // 确保使用正确的ID字段，可能是employeeId或id
  const employeeData = {
    ...employee,
    employeeId: employee.employeeId || employee.id
  }
  Object.assign(employeeForm.value, employeeData)
  showEditDialog.value = true
}

const handleDelete = async (employee) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个员工吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 兼容 employeeId 和 id
    const employeeId = employee.employeeId || employee.id
    await employeeStore.deleteEmployee(employeeId)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败，请重试')
    }
  }
}

const handleRefreshEmployees = async () => {
  try {
    await employeeStore.fetchEmployees()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败，请重试')
  }
}

const handleSaveEmployee = async () => {
  employeeFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const qualificationValue = Array.isArray(employeeForm.value.certifications)
        ? employeeForm.value.certifications.join(',')
        : employeeForm.value.certifications;
      if (editingEmployee.value) {
        // 编辑 - 使用正确的ID字段
        const employeeId = editingEmployee.value.employeeId || editingEmployee.value.id
        await employeeStore.updateEmployee(employeeId, {
          ...employeeForm.value,
          entryDate: employeeForm.value.joinDate, // 适配后端字段
          qualification: qualificationValue // 适配后端字段
        })
        ElMessage.success('员工信息更新成功')
      } else {
        // 新增
        const newEmployee = {
          ...employeeForm.value,
          entryDate: employeeForm.value.joinDate, // 适配后端字段
          qualification: qualificationValue // 适配后端字段
        }
        await employeeStore.addEmployee(newEmployee)
        ElMessage.success('员工添加成功')
      }
      showEditDialog.value = false
      editingEmployee.value = null
      Object.assign(employeeForm.value, {
        name: '',
        email: '',
        position: '',
        department: '',
        certifications: [],
        joinDate: ''
      })
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    }
  })
}

// 新增的响应式数据
const showBatchDialog = ref(false)
const showEditShiftDialog = ref(false)
const editingShift = ref(null)
const scheduleView = ref('calendar') // 'calendar' 或 'list'
const scheduleSearch = ref({
  name: '',
  dateRange: [],
  shiftType: '',
  status: ''
})
const hasEditPermission = ref(true) // 编辑权限，实际应用中应从用户信息获取

// 批量排班表单
const batchForm = ref({
  employees: [],
  dates: [],
  shiftType: ''
})

// 排班表单
const shiftForm = ref({
  employeeId: '',
  employeeName: '',
  date: '',
  type: '',
  time: '',
  creator: '管理员' // 实际应用中应从登录信息获取
})

// 表单验证规则
const batchRules = {
  employees: [{ required: true, message: '请选择员工', trigger: 'blur' }],
  dates: [{ required: true, message: '请选择日期', trigger: 'blur' }],
  shiftType: [{ required: true, message: '请选择班次类型', trigger: 'blur' }]
}


// 禁用今天及之前的日期
const disablePastDate = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date <= today
}

// 计算属性：过滤后的排班数据（只展示有排班的员工）
const filteredScheduleDays = computed(() => {
  // 生成日期区间
  let days = [];
  let start, end;
  if (scheduleSearch.value.dateRange && scheduleSearch.value.dateRange.length === 2) {
    start = new Date(scheduleSearch.value.dateRange[0]);
    end = new Date(scheduleSearch.value.dateRange[1]);
  } else {
    // 默认今天前后各3天
    const today = new Date();
    start = new Date(today);
    start.setDate(today.getDate() - 3);
    end = new Date(today);
    end.setDate(today.getDate() + 3);
  }
  start.setHours(0, 0, 0, 0);
  end.setHours(0, 0, 0, 0);

  for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
    days.push(formatDate(new Date(d)));
  }

  // 按天分组，只保留有排班的员工
  return days.map(dateStr => {
    // 找到当天所有排班
    const shifts = employeeStore.schedules
      .filter(s => s.scheduleDate === dateStr)
      .map(s => ({
        id: s.id,
        employee: s.employeeName,
        employeeId: s.employeeId,
        date: dateStr,
        type: s.shiftType,
        time: getShiftInfo(s.shiftType)?.time || '',
        status: 'active'
      }));
    return { date: dateStr, shifts };
  });
})

// 计算属性：列表视图的排班数据
const filteredShifts = computed(() => {
  // 直接使用API返回的排班数据，转换为列表格式
  let shifts = employeeStore.schedules.map(schedule => ({
    id: schedule.id,
    employee: schedule.employeeName,
    employeeId: schedule.employeeId,
    date: schedule.scheduleDate,
    type: schedule.shiftType,
    time: getShiftInfo(schedule.shiftType)?.time || '',
    status: 'active'
  }));

  // 应用查询条件
  if (scheduleSearch.value.name) {
    shifts = shifts.filter(shift =>
      shift.employee.includes(scheduleSearch.value.name))
  }

  if (scheduleSearch.value.dateRange && scheduleSearch.value.dateRange.length === 2) {
    const [start, end] = scheduleSearch.value.dateRange
    shifts = shifts.filter(shift => {
      const date = parseDate(shift.date)
      return date >= start && date <= end
    })
  }

  if (scheduleSearch.value.shiftType) {
    shifts = shifts.filter(shift => shift.type === scheduleSearch.value.shiftType)
  }

  if (scheduleSearch.value.status) {
    shifts = shifts.filter(shift => shift.status === scheduleSearch.value.status)
  }

  return shifts
})

// 新增方法
const handleScheduleSearch = async () => {
  try {
    const params = {
      pageNum: scheduleCurrentPage.value,
      pageSize: schedulePageSize.value
    };

    // 添加查询条件
    if (scheduleSearch.value.name) {
      params.employeeName = scheduleSearch.value.name;
    }
    if (scheduleSearch.value.dateRange && scheduleSearch.value.dateRange.length === 2) {
      params.startDate = formatDate(scheduleSearch.value.dateRange[0]);
      params.endDate = formatDate(scheduleSearch.value.dateRange[1]);
    }
    if (scheduleSearch.value.shiftType) {
      params.shiftType = scheduleSearch.value.shiftType;
    }

    await employeeStore.fetchSchedules(params);
    ElMessage.success('查询成功');
  } catch (error) {
    ElMessage.error('查询失败，请重试');
  }
}

const resetScheduleSearch = async () => {
  scheduleSearch.value = {
    name: '',
    dateRange: [],
    shiftType: '',
    status: ''
  }
  // 重置后重新获取数据
  try {
    await employeeStore.fetchSchedules({
      pageNum: 1,
      pageSize: schedulePageSize.value
    });
    scheduleCurrentPage.value = 1;
    ElMessage.success('重置成功');
  } catch (error) {
    ElMessage.error('重置失败，请重试');
  }
}
const batchFormRef = ref(null)
const handleBatchSchedule = async () => {
  batchFormRef.value?.validate(async (valid) => {
    if (!valid) return

    // robust: 保证 employees 一定是字符串数组
    let employees = batchForm.value.employees;
    if (!Array.isArray(employees)) {
      employees = employees ? [employees] : [];
    }
    // 转为数字数组，过滤掉无效值
    const employeeIds = employees
      .map(eid => Number(eid))
      .filter(id => !isNaN(id) && id > 0);
    console.log('选中员工原始值:', batchForm.value.employees);
    console.log('最终提交的 employeeIds:', employeeIds);

    const dates = batchForm.value.dates.map(date => formatDate(date));
    const shiftType = batchForm.value.shiftType;

    const scheduleData = {
      employeeIds,
      dates,
      shiftType
    };
    console.log('批量排班数据:', scheduleData);

    try {
      const response = await employeeStore.batchSchedule(scheduleData);
      if (response && response.code === 200) {
        const { successCount, conflictCount, conflicts } = response.data
        if (conflictCount > 0) {
          ElMessage.warning(`批量排班完成，成功${successCount}条，冲突${conflictCount}条: ${conflicts.join('; ')}`)
        } else {
          ElMessage.success(`成功添加 ${successCount} 条排班记录`)
        }
        showBatchDialog.value = false
        batchForm.value = {
          employees: [],
          dates: [],
          shiftType: ''
        }
      } else {
        ElMessage.error(response?.errorMsg || '批量排班失败');
      }
    } catch (error) {
      ElMessage.error('批量排班失败，请重试');
    }
  });
}


const handleEditShift = (shift) => {
  editingShift.value = shift
  shiftForm.value = {
    employeeId: shift.employeeId,
    employeeName: shift.employee,
    date: parseDate(shift.date),
    type: shift.type,
    time: shift.time,
    status: shift.status,
    creator: shift.creator
  }
  showEditShiftDialog.value = true
}

const handleDeleteShift = async (shift) => {
  try {
    await ElMessageBox.confirm('确定删除这条排班记录吗？', '确认删除', { type: 'warning' });
    await employeeStore.deleteSchedule(Number(shift.id));
    // 删除后刷新
    await employeeStore.fetchSchedules({
      pageNum: scheduleCurrentPage.value,
      pageSize: schedulePageSize.value,
      ...getScheduleSearchParams()
    });
    ElMessage.success('删除成功');
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      ElMessage.error('删除失败，请重试');
    }
  }
};


// 辅助方法
const getShiftInfo = (type) => {
  const shiftTypes = {
    'morning': { time: '09:00-12:00', color: 'primary' },
    'afternoon': { time: '13:00-21:00', color: 'success' },
    'full-day': { time: '09:00-21:00', color: 'danger' }
  }
  return shiftTypes[type]
}



const isToday = (dateStr) => {
  const today = new Date()
  return formatDate(today) === dateStr
}

const isPastDate = (dateStr) => {
  const today = new Date()
  const date = parseDate(dateStr)
  return date < today
}

const canEditShift = (shift) => {
  // 实际应用中应根据权限和日期判断
  return !isPastDate(shift.date)
}

const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const y = d.getFullYear();
  const m = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');
  return `${y}-${m}-${day}`;
}

const parseDate = (dateStr) => {
  if (!dateStr) return null
  const parts = dateStr.split('-')
  return new Date(parts[0], parts[1] - 1, parts[2])
}

const formatShiftType = (type) => {
  const types = {
    'morning': '上午班',
    'afternoon': '下午班',
    'full-day': '全天班'
  }
  return types[type] || type
}

const getShiftTagType = (type) => {
  const types = {
    'morning': 'primary',
    'afternoon': 'success',
    'full-day': 'danger'
  }
  return types[type] || 'info'
}

const getShiftClass1 = (type) => {
  const typeClass = {
    'morning': 'shift-morning', // 蓝色
    'afternoon': 'shift-afternoon', // 绿色
    'full-day': 'shift-full-day' // 红色
  }[type] || ''
  return `${typeClass}`
}

// 在 script 部分的 performanceList ref 上方添加：
const orderStore = useOrderStore()

// 新增：合并服务订单和商品订单的绩效统计
const performanceRawList = computed(() => {
  // 服务订单
  const serviceOrders = orderStore.orders || []
  // 商品订单
  const productOrders = productOrderStore.orders || []

  return (employeeStore.employees || []).map(emp => {
    // 服务订单统计
    const serviceOrderList = serviceOrders.filter(o => o.employeeName === emp.name)
    const serviceOrderCount = serviceOrderList.length
    const serviceSalesAmount = serviceOrderList.reduce((sum, o) => sum + (o.actualAmount || 0), 0)

    // 商品订单统计
    const productOrderList = productOrders.filter(o => o.employeeName === emp.name)
    const productOrderCount = productOrderList.length
    const productSalesAmount = productOrderList.reduce((sum, o) => sum + (o.totalAmount || 0), 0)

    // 合计
    const totalOrderCount = serviceOrderCount + productOrderCount
    const totalSalesAmount = serviceSalesAmount + productSalesAmount

    // 绩效总分自动计算
    // 权重：订单数30%，销售额40%，工作态度30%，销售额单位万元
    const attitudeScore=0 // 默认分数，可后续编辑
    const weights = { orderCount: 0.3, salesAmount: 0.4, attitudeScore: 0.3 }
    const normalizedSales = totalSalesAmount / 10000 // 万元
    const normalizedAttitude = attitudeScore // 1-100分
    const totalScore = (
      totalOrderCount * weights.orderCount +
      normalizedSales * weights.salesAmount +
      normalizedAttitude * weights.attitudeScore
    ).toFixed(1)

    return {
      id: emp.employeeId || emp.id, // 直接用员工主键
      employeeId: emp.employeeId || emp.id,
      employeeName: emp.name,
      orderCount: totalOrderCount,
      salesAmount: totalSalesAmount,
      attitudeScore,
      totalScore,
      status: 'draft'
    }
  })
})
const performanceList = ref([])

// 绩效评估相关数据
const performanceForm = ref({
  id: '',
  employeeId: '',
  employeeName: '',
  orderCount: 0,
  salesAmount: 0,
  attitudeScore: 0,
  totalScore: 0,
  status: 'draft'
})

const performanceQuery = ref({
  employeeId: '',
  employeeName: '',
  minScore: null,
  maxScore: null,
})

const performanceLoading = ref(false)
const performancePagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})



const performanceRules = {
  attitudeScore: [
    { required: true, message: '请输入工作态度得分', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 1 || value > 100) {
          callback(new Error('请输入1-100分'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
}

// 绩效评估方法
const calculateTotalScore = () => {
  // 权重配置
  const weights = {
    orderCount: 0.3,
    salesAmount: 0.4,
    attitudeScore: 0.3
  }

  // 标准化处理
  const normalizedSales = performanceForm.value.salesAmount / 10000 // 将销售额标准化为万元
  const normalizedAttitudeScore = performanceForm.value.attitudeScore * 20 // 将1-100分转换为20-100分

  // 计算总分
  performanceForm.value.totalScore = (
    performanceForm.value.orderCount * weights.orderCount +
    normalizedSales * weights.salesAmount +
    normalizedAttitudeScore * weights.attitudeScore
  ).toFixed(1)
}

const submitPerformanceEdit = async () => {
  performanceFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const res = await employeeStore.updatePerformance({
        id: Number(performanceForm.value.id),
        performance: performanceForm.value.totalScore,
        workScore: performanceForm.value.attitudeScore
      });
      if (res.code === 200) {
        ElMessage.success('保存成功');
        showPerformanceEditDialog.value = false;
        await fetchPerformanceList();
      } else {
        ElMessage.error(res.message || '保存失败');
      }
    } catch (e) {
      ElMessage.error('保存失败');
    }
  });
};

const handleDeletePerformance = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除此绩效记录吗?', '提示', { type: 'warning' });
    const res = await employeeStore.deletePerformance(row.id);
    if (res.code === 200) {
      ElMessage.success('删除成功');
      fetchPerformanceList();
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handlePerformanceQuery = () => {
  performancePagination.page = 1
  fetchPerformanceList()
}

const resetPerformanceQuery = () => {
  performanceQuery.value = {
    employeeId: '',
    employeeName: '',
    minScore: null,
    maxScore: null,
  }
  // 立即刷新表格
  fetchPerformanceList()
}

const fetchPerformanceList = async () => {
  performanceLoading.value = true;
  try {
    const params = {
      pageNum: performancePagination.page,
      pageSize: performancePagination.pageSize,
      minScore: performanceQuery.value.minScore,
      maxScore: performanceQuery.value.maxScore
    };
    // 只按 employeeId 查询，不再传 name
    if (performanceQuery.value.employeeId) {
      params.employeeId = performanceQuery.value.employeeId;
    }
    await employeeStore.fetchPerformanceList(params);
    performancePagination.total = employeeStore.performanceTotal;
  } catch (e) {
    ElMessage.error('获取绩效数据失败');
  } finally {
    performanceLoading.value = false;
  }
};

const handlePerformanceSort = ({ prop, order }) => {
  if (order) {
    performanceList.value.sort((a, b) => {
      if (order === 'ascending') {
        return a[prop] - b[prop]
      } else {
        return b[prop] - a[prop]
      }
    })
  }
}

const handleEditPerformance = (row) => {
  // 只允许编辑态度分，订单数和销售额用前端统计
  // 先找到本地统计
  const local = performanceRawList.value.find(e => String(e.employeeId) === String(row.employeeId || row.id))
  performanceForm.value = {
    id: row.employeeId || row.id,
    employeeId: row.employeeId || row.id,
    employeeName: row.employeeName || row.name,
    orderCount: local ? local.orderCount : 0,
    salesAmount: local ? local.salesAmount : 0,
    attitudeScore: row.attitudeScore ?? row.workScore ?? 0,
    totalScore: row.totalScore ?? row.performance ?? 0,
    status: row.status
  }
  showPerformanceEditDialog.value = true
}

// 监听态度分变化自动计算绩效总分
watch(() => performanceForm.value.attitudeScore, (val) => {
  // 绩效总分自动计算，权重：订单数30%，销售额40%，工作态度30%，销售额单位万元
  const weights = { orderCount: 0.3, salesAmount: 0.4, attitudeScore: 0.3 }
  const normalizedSales = (performanceForm.value.salesAmount || 0) / 10000
  const normalizedAttitude = val || 0
  performanceForm.value.totalScore = (
    (performanceForm.value.orderCount || 0) * weights.orderCount +
    normalizedSales * weights.salesAmount +
    normalizedAttitude * weights.attitudeScore
  ).toFixed(2)
})

const handlePerformanceSizeChange = (val) => {
  performancePagination.pageSize = val
  performancePagination.page = 1
}

const handlePerformancePageChange = (val) => {
  performancePagination.page = val
}



onMounted(async () => {
  try {
    await employeeStore.fetchEmployees(employeeCurrentPage.value, employeePageSize.value)
    await employeeStore.fetchAllEmployees() // 加载全量员工
  } catch (error) {
    ElMessage.error('获取员工数据失败，请检查网络连接或联系管理员')
    console.error('初始化员工数据失败:', error)
  }

  // 获取排班数据
  try {
    await employeeStore.fetchSchedules({
      pageNum: scheduleCurrentPage.value,
      pageSize: schedulePageSize.value
    })
  } catch (error) {
    ElMessage.error('获取排班数据失败，请检查网络连接或联系管理员')
    console.error('初始化排班数据失败:', error)
  }

  // 新增：获取商品订单数据
  try {
    await productOrderStore.fetchOrders()
  } catch (error) {
    ElMessage.error('获取商品订单数据失败')
    console.error('初始化商品订单数据失败:', error)
  }

  fetchPerformanceList()
})


// generateId函数已不再需要，因为ID由后端生成

// 分页相关变量
const employeeCurrentPage = ref(1)
const employeePageSize = ref(10)
const scheduleCurrentPage = ref(1)
const schedulePageSize = ref(10)

// 排班列表分页后的数据
const pagedShifts = computed(() => {
  // 直接使用API返回的数据，分页由后端处理
  return filteredShifts.value
})

const phoneRules = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
];
const emailRules = [
  { required: true, message: '请输入邮箱', trigger: 'blur' },
  { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
];

// 编辑绩效对话框逻辑
const showPerformanceEditDialog = ref(false)

const handleEmployeePageChange = (page) => {
  employeeCurrentPage.value = page
  employeeStore.fetchEmployees(page, employeePageSize.value)
}
const handleEmployeeSizeChange = (size) => {
  employeePageSize.value = size
  employeeCurrentPage.value = 1
  employeeStore.fetchEmployees(1, size)
}

// 排班分页处理方法
const handleSchedulePageChange = async (page) => {
  scheduleCurrentPage.value = page
  try {
    await employeeStore.fetchSchedules({
      pageNum: page,
      pageSize: schedulePageSize.value,
      ...getScheduleSearchParams()
    })
  } catch (error) {
    ElMessage.error('获取排班数据失败')
  }
}

const handleScheduleSizeChange = async (size) => {
  schedulePageSize.value = size
  scheduleCurrentPage.value = 1
  try {
    await employeeStore.fetchSchedules({
      pageNum: 1,
      pageSize: size,
      ...getScheduleSearchParams()
    })
  } catch (error) {
    ElMessage.error('获取排班数据失败')
  }
}

// 获取排班查询参数的辅助方法
const getScheduleSearchParams = () => {
  const params = {}
  if (scheduleSearch.value.name) {
    params.employeeName = scheduleSearch.value.name
  }
  if (scheduleSearch.value.dateRange && scheduleSearch.value.dateRange.length === 2) {
    params.startDate = formatDate(scheduleSearch.value.dateRange[0])
    params.endDate = formatDate(scheduleSearch.value.dateRange[1])
  }
  if (scheduleSearch.value.shiftType) {
    params.shiftType = scheduleSearch.value.shiftType
  }
  return params
}

const performanceFormRef = ref(null);

const handleResetEmployeeSearch = async () => {
  searchKeyword.value = ''
  try {
    await employeeStore.fetchEmployees(1, employeePageSize.value)
    employeeCurrentPage.value = 1
    ElMessage.success('重置成功')
  } catch (error) {
    ElMessage.error('重置失败，请重试')
  }
}

const handleEmployeeSearch = async () => {
  try {
    await employeeStore.fetchEmployees(1, employeePageSize.value, searchKeyword.value)
    employeeCurrentPage.value = 1
    // 可选：ElMessage.success('查询成功')
  } catch (error) {
    ElMessage.error('查询失败，请重试')
  }
}

// 合并前端统计和后端绩效分
const mergedPerformanceList = computed(() => {
  // 以员工ID为主键合并
  const perfMap = new Map()
  // 先用前端统计填充订单数、销售额
  performanceRawList.value.forEach(item => {
    perfMap.set(String(item.employeeId), {
      employeeId: item.employeeId,
      employeeName: item.employeeName,
      orderCount: item.orderCount,
      salesAmount: item.salesAmount,
      attitudeScore: item.attitudeScore ?? item.workScore ?? 0,
      totalScore: item.totalScore ?? item.performance ?? 0,
      status: item.status
    })
  })
  // 用后端接口覆盖绩效分、工作态度分
  ;(employeeStore.performanceList || []).forEach(item => {
    const key = String(item.employeeId || item.id)
    if (perfMap.has(key)) {
      const target = perfMap.get(key)
      target.attitudeScore = item.attitudeScore ?? item.workScore ?? target.attitudeScore ?? 0
      target.totalScore = item.totalScore ?? item.performance ?? target.totalScore ?? 0
    } else {
      // 后端有但前端没有的员工
      perfMap.set(key, {
        employeeId: item.employeeId || item.id,
        employeeName: item.employeeName || item.name,
        orderCount: 0,
        salesAmount: 0,
        attitudeScore: item.attitudeScore ?? item.workScore ?? 0,
        totalScore: item.totalScore ?? item.performance ?? 0,
        status: item.status
      })
    }
  })
  return Array.from(perfMap.values() || [])
})

// 分页处理
const pagedMergedPerformanceList = computed(() => {
  const start = (performancePagination.page - 1) * performancePagination.pageSize
  const end = start + performancePagination.pageSize
  return (mergedPerformanceList.value || []).slice(start, end)
})

</script>

<style scoped>
.employee-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  width: 100%;
}

.tabs-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

}

.tab-content {
  margin-top: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.employee-table-card {
  margin-top: 20px;
}

.employee-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.employee-details {
  display: flex;
  flex-direction: column;
}

.employee-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.employee-email {
  color: #909399;
  font-size: 12px;
}

.certifications {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.cert-tag {
  margin-right: 4px;
}

.schedule-card {
  margin-top: 20px;
  width: 100%;
  overflow-x: auto;
}

.schedule-grid {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.schedule-day {
  min-width: 160px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: white;
  flex-shrink: 0;
}

.day-header {
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  text-align: center;
}

.shift-item {
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 6px;
  font-size: 12px;
}

.shift-time {
  font-weight: 600;
  margin-bottom: 4px;
}

.shift-employee {
  font-size: 11px;
  opacity: 0.8;
}

.metrics-row {
  margin-bottom: 20px;
}

.metric-card {
  height: 120px;
}

.metric-content {
  text-align: center;
}

.metric-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.metric-value {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 8px;
}

.value-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.value-growth {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
  color: #67c23a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 新增的样式 */
.schedule-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.schedule-search {
  display: flex;
  align-items: center;
}

.view-toggle {
  margin-bottom: 15px;
  text-align: right;
}

.schedule-day.today {
  border: 2px solid #1890ff;
  background-color: #f0f9ff;
}

.day-header .day-date {
  font-size: 12px;
  color: #909399;
}

.shift-morning {
  background-color: #f0f9ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
}

.shift-afternoon {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #52c41a;
}

.shift-full-day {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  color: #f5222d;
}

.shift-active {
  /* 默认状态 */
}

.shift-leave {
  opacity: 0.6;
  text-decoration: line-through;
}

.shift-actions {
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
  gap: 5px;
}

/* 分数分隔符 */
.score-separator {
  margin: 0 10px;
  color: #999;
}

/* 高亮显示优秀员工 */
.high-score {
  color: #f56c6c;
  font-weight: bold;
}

/* 表格操作按钮 */
.el-table .cell .el-button {
  margin: 2px 0;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 新增的样式 */
.shift-empty {
  background: #f5f7fa;
  color: #bbb;
  border: 1px dashed #e4e7ed;
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 6px;
  font-size: 12px;
}
</style>
